<template>
  <div class="timeline-container">
    <div class="hour-marks">
      <div v-for="hour in 24" :key="hour" class="hour-mark">{{ hour }}</div>
    </div>
    <div class="progress-container">
      <div
          v-for="hour in 24"
          :key="hour"
          :class="{ 'selected': isHourSelected(hour) }"
          class="hour-block"
          @mousedown="startSelecting(hour)"
          @mouseover="hoverHour(hour)"
          @mouseup="endSelection"
      ></div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedHours: [],
      isSelecting: false,
      startHour: null,
      endHour: null,
      currentSelection: [],
      selectionMode: null // 'select' or 'deselect'
    };
  },
  props: {
    initialSelectedHours: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    initialSelectedHours: {
      handler(newValue) {
        this.selectedHours = [...newValue];
      },
      immediate: true // 立即执行该方法
    }
  },
  created() {
    this.selectedHours = [...this.initialSelectedHours];
  },
  methods: {
    startSelecting(hour) {
      this.isSelecting = true;
      this.startHour = hour;
      this.endHour = hour;

      if (this.isHourSelected(hour)) {
        this.selectionMode = 'deselect';
      } else {
        this.selectionMode = 'select';
      }

      this.updateSelection();
    },
    hoverHour(hour) {
      if (this.isSelecting) {
        this.endHour = hour;
        this.updateSelection();
      }
    },
    endSelection() {
      if (this.selectionMode === 'select') {
        this.selectedHours = [...this.selectedHours, ...this.currentSelection];
      } else if (this.selectionMode === 'deselect') {
        this.selectedHours = this.selectedHours.filter(hour => !this.currentSelection.includes(hour));
      }

      this.currentSelection = [];
      this.isSelecting = false;
      this.$emit('selection-changed', this.selectedHours);
    },
    updateSelection() {
      this.currentSelection = [];
      const [start, end] = [this.startHour, this.endHour].sort((a, b) => a - b);

      for (let i = start; i <= end; i++) {
        this.currentSelection.push(i);
      }
    },
    isHourSelected(hour) {
      return this.selectedHours.includes(hour) || this.currentSelection.includes(hour);
    }
  }
};
</script>

<style scoped>
.timeline-container {
  width: 100%;
  position: relative;
  margin-bottom: 10px;
}

.hour-marks, .progress-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 5px;
  overflow: hidden;
}

.hour-mark {
  flex: 1;
  text-align: center;
}

.progress-container {
  height: 20px;
  background: rgba(50, 63, 88, 1.00);
  position: relative;
  margin-top: 10px;
}

.hour-block {
  flex: 1;
  height: 100%;
  transition: background 0.3s;
}

.hour-block.selected {
  background: rgba(154, 210, 255, 1.00);
}
</style>
